package ru.minidoc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.SqlTypeValue;
import org.springframework.jdbc.core.StatementCreatorUtils;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;

public class AbstractDao {
    protected DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    protected int queryAndReturnIdentity(String sql, Object[] args) {
        Connection con = DataSourceUtils.getConnection(dataSource);
        Statement stmt = null;
        try {
            PreparedStatement ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    Object arg = args[i];
                    if (arg instanceof SqlParameterValue) {
                        SqlParameterValue paramValue = (SqlParameterValue) arg;
                        StatementCreatorUtils.setParameterValue(ps, i + 1, paramValue, paramValue.getValue());
                    } else {
                        StatementCreatorUtils.setParameterValue(ps, i + 1, SqlTypeValue.TYPE_UNKNOWN, arg);
                    }
                }
            }
            ps.executeUpdate();
            stmt = con.createStatement();
            stmt.execute("CALL IDENTITY();");
            ResultSet resultSet = stmt.getResultSet();
            resultSet.next();
            return resultSet.getInt(1);
        } catch (SQLException ex) {
            // Release Connection early, to avoid potential connection pool
            // deadlock
            // in the case when the exception translator hasn't been initialized
            // yet.
            JdbcUtils.closeStatement(stmt);
            stmt = null;
            DataSourceUtils.releaseConnection(con, dataSource);
            con = null;
            throw new RuntimeException(ex);
        } finally {
            JdbcUtils.closeStatement(stmt);
            DataSourceUtils.releaseConnection(con, dataSource);
        }

    }
}
